import time
import json


def compute_latency(device_list):
    with open('data/commit_index', 'r') as cf:
        commit_index = int(cf.readline())
    with open('data/log.json', 'r') as lf:
        full_data = json.load(lf)
    log_data = full_data[commit_index - 1]['info']
    latency = 0
    current_time = float(time.time())
    count = 0
    for device_id in device_list:
        if device_id not in log_data.keys():
            continue
        count += 1
        latency += (current_time - float(log_data[device_id][0])) ** 2
    latency **= 0.5
    latency /= count
    write_line = str(current_time) + ' ' + str(latency) + '\n'
    print(write_line)
    with open('data/experiment.txt', 'a') as ef:
        ef.write(write_line)


if __name__ == '__main__':
    with open('data/configure.json', 'r') as f:
        data = json.load(f)
        node_list = [data['id']] + list(data['peers'].keys())
    while True:
        time.sleep(0.2)
        try:
            compute_latency(node_list)
        except:
            pass
